package com.baobao.demo;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

public class CommandHelloWorld extends HystrixCommand<Response> {
	private static Logger log = LoggerFactory.getLogger(CommandHelloWorld.class);
	private final String name;

	public CommandHelloWorld(String name) {

		
		super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")) // 必须
				.andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(300)// 超时时间
						.withCircuitBreakerRequestVolumeThreshold(3)// 10秒内，请求在5个及以上，有50%失败的情况，开启断路器
						.withCircuitBreakerErrorThresholdPercentage(50))
				.andCommandKey(HystrixCommandKey.Factory.asKey("Example")) // 可选,默认
																			// 使用
																			// this.getClass().getSimpleName();
				.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter().withCoreSize(4)));// 最大并发数
		this.name = name;
	}

	@Override
	protected Response run() throws IOException {
		
		log.info("执行了run");
		Request request = new Request.Builder().url(name).build();
		return new OkHttpClient().newCall(request).execute();
	}

	@Override
	protected Response getFallback() {
		return null;
	}

}
